/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package velocity;

import java.io.StringWriter;
import java.util.Properties;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

/**
 *
 * @author WangShuai
 */
public class Demo1 {

    public static void main(String[] args) {
        
        Properties properties = new Properties();
        //设置模板的路径:
        //1.文件系统
        //String fileDir = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        //properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,fileDir);
        //2.ClassPath: 模板文件需要放在class目录下，而不是src目录下
        properties.setProperty(Velocity.RESOURCE_LOADER,"class");
        properties.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        //初始花velocity 让设置的路径生效,否则不会生效
        Velocity.init(properties);
        
        VelocityContext context = new VelocityContext();

        context.put("name", new String("Velocity"));

        Template template = null;

        try {
            template = Velocity.getTemplate("1.vm");
        } catch (ResourceNotFoundException rnfe) {
            // couldn't find the template
            rnfe.printStackTrace();
        } catch (ParseErrorException pee) {
            // syntax error: problem parsing the template
            pee.printStackTrace();
        } catch (MethodInvocationException mie) {
            // something invoked in the template
            // threw an exception
            mie.printStackTrace();
        } catch (Exception e) {
        }

        StringWriter sw = new StringWriter();

        template.merge(context, sw);

        System.out.println(sw.toString());
    }
}
